Im trying to create a image gallery using UICollectionView. But the dispatch_queue does not seem to download image instead it skips the download and continues executing the next statement.
Below is my code:
for(int i=0;i<[_urlArray count];i++){
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0), ^{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[_urlArray objectAtIndex:i]]];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [path stringByAppendingString:[NSString stringWithFormat:#"%d.png",i]];
NSLog(#"img data %#",data);
[data writeToFile:path atomically:YES];
UIImage *theImage=[UIImage imageNamed:path];
[_imgArray addObject:theImage];
dispatch_async(dispatch_get_main_queue(), ^{
});
});
}
I even tried AFNetworking and SDWebImage. But did not help me. Please help me with this. Thank you.
Have you tried to store all data and Images from URL to iOS Cache memory or any DB?
Related
The workflow of my function is the following:
retrieve a jpg through python get request
save image as png (even though is downloaded as jpg) on disk
use imageio to read from disk image and transform it into numpy array
work with the array
This is what I do to save:
response = requests.get(urlstring, params=params)
if response.status_code == 200:
with open('PATH%d.png' % imagenumber, 'wb') as output:
output.write(response.content)
This is what I do to load and transform png into np.array
imagearray = im.imread('PATH%d.png' % imagenumber)
Since I don't need to store permanently what I download I tried to modify my function in order to transform the response.content in a Numpy array directly. Unfortunately every imageio like library works in the same way reading a uri from the disk and converting it to a np.array.
I tried this but obviously it didn't work since it need a uri in input
response = requests.get(urlstring, params=params)
imagearray = im.imread(response.content))
Is there any way to overcome this issue? How can I transform my response.content in a np.array?
imageio.imread is able to read from urls:
import imageio
url = "https://example_url.com/image.jpg"
# image is going to be type <class 'imageio.core.util.Image'>
# that's just an extension of np.ndarray with a meta attribute
image = imageio.imread(url)
You can look for more information in the documentation, they also have examples: https://imageio.readthedocs.io/en/stable/examples.html
You can use BytesIO as file to skip writing to an actual file.
bites = BytesIO(base64.b64decode(response.content))
Now you have it as BytesIO, so you can use it just like a file:
img = Image.open(bites)
img_np = np.array(im)
I converted ipad signature to png image successfully using UIImagePNGRrepresentation(Image). Now I want to store this Image from swift to a SQL Server database using a web service. I have not any idea about how do this?
This is my swift code
UIGraphicsBeginImageContextWithOptions(self.signatureMainImageview.bounds.size, false, 0.0)
self.signatureMainImageview.image?.drawInRect(CGRectMake(0, 0, self.signatureMainImageview.frame.size.width, self.signatureMainImageview.frame.size.height))
let SaveImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let image = UIImagePNGRepresentation(SaveImage)
var CardDataObj = structCardData()
CardDataObj.CustomerSignature = image!
let requestCardData = NSMutableURLRequest(URL: NSURL(string: "http://URL")!)
requestCardData.HTTPMethod = "POST"
let postString = CardDataObj.jsonRepresentation
requestCardData.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(requestCardData) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
Now I want to know how to get this image in webservice? which datatype use in webservice for image? which datatype use in sql for image? How to send this image to sql?
Rather than a data task you need an upload task. Either uploadTaskWithRequest:fromData:completionHandler or its file or stream variants
In order to begin the task you need to call task.resume()
It also helps to retrieve the response if you cast to HTTPURLResponse like so:
if let response = response as? NSHTTPURLResponse {
response.statusCode
response.allHeaderFields
}
I wrote a blogpost on uploading using a stream, which might be of some use. Here's also a more general post about NSURLSession.
The first blogpost linked to will give you some server-side code in PHP to receive a stream, but if you are uncertain about what to do on the SQL I'd recommended breaking this question into two and asking that question separately.
Want to share video using UIActivityViewController with its thumbnail and playbutton icon.
I used .mp4 url but facebook shows url not thumbnail.
how to make possible to show video(thumbnail with play button) on Facebook without using following code, because it doesnt work.
ALAsset * asset = [[ALAsset alloc] init];
[asset setVideoAtPath:urlToVideoFile completionBlock:NULL];
NSArray * activityItems = #[asset];
UIActivityViewController * activityController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:NULL]
The code which you have put is adding asset into array, don't put asset directly instead put url and try.
I am using Apple Map's in my app and on my view i want to show the driving direction from the user location to the current location that i have on the view, now i just want all this inside my app only i.e i can show the driving direction's on the mapview, I have tried using the apple map application but after i make call to it from my application it takes me to apple's map application where i get the driving direction's but i can not return back into my application so i am thinking that i can do something in my application itself so that i can get the driving directions on my current view itself ..
NSString* addr = [NSString stringWithFormat:#"http://maps.apple.com/maps?daddr=%1.6f,%1.6f&saddr=%1.6f,%1.6f",coordinate.latitude,coordinate.longitude,mapView.userLocation.coordinate.latitude,mapView.userLocation.coordinate.longitude];
NSURL* url = [[NSURL alloc] initWithString:[addr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:url];
this code takes me to the apple's map app from my native app but i can't return directly back to my app.is there a possible solution so that i can move back to my APP AFTER GETTING THE DRIVING DIRECTIONS ?? (webview didnot work for me.can i add a back button on apple's app or what ).Please help.... Thanks a lot !!
Or Please can any one suggest me a better code for implementing so that i can do all of that in my application only ?
I want an in-app map depicting the navigation routes and driving directions...
This is not the way to achieve the directions,
I have made a sample for you which covers all the iOS versions, New Google Maps and the iOS 6 tom tom maps as well.
Here it is:
if([[[UIDevice currentDevice] systemVersion] compare:#"6.0" options:NSNumericSearch] == NSOrderedDescending){
//6.0 or above
NSString *Destinationlatlong =[NSString stringWithFormat:#"%#,%#",your.latitude,your.longitude];
NSString* addr = [NSString stringWithFormat:#"comgooglemaps://?saddr=%f,%f&daddr=%#",[AppDelegate zDelegate].location.coordinate.latitude,[AppDelegate zDelegate].location.coordinate.longitude, Destinationlatlong];
addr=[addr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [[[NSURL alloc] initWithString:addr]autorelease];
// NSLog(#"url %#",url);
if ([[UIApplication sharedApplication]canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}else{
CLLocationCoordinate2D coords =
CLLocationCoordinate2DMake([your.latitude doubleValue],[your.longitude doubleValue]);
MKPlacemark *placeMark = [[MKPlacemark alloc]
initWithCoordinate:coords addressDictionary:nil];
MKMapItem *destination = [[MKMapItem alloc]initWithPlacemark:placeMark];
[destination openInMapsWithLaunchOptions:nil];
}
}else{
NSString *Destinationlatlong =[NSString stringWithFormat:#"%#,%#",your.latitude,your.longitude];
NSString* addr = [NSString stringWithFormat:#"http://maps.google.com/maps?saddr=Current+Location&daddr=%#",Destinationlatlong];
addr=[addr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [[[NSURL alloc] initWithString:addr]autorelease];
// NSLog(#"url %#",url);
if ([[UIApplication sharedApplication]canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}else{
UIAlertView *alert=[[[UIAlertView alloc] initWithTitle:#"Warning!" message:#"Device does not support this functionality" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles: nil]autorelease] ;
[alert show];
}
}
This should get you started. In short, get driving instruction from google api in json, parse it, and display it on your own map using MKPolyline
http://iosguy.com/2012/05/22/tracing-routes-with-mapkit/
I am trying make a call to the fitbit API.
I am unsure how to input the HTTP request shown below into my Objective C code in order to make this call and handle the response.
POST /oauth/request_token HTTP/1.1
Host: api.fitbit.com
Authorization: OAuth oauth_consumer_key="fitbit-example-client-application",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1270248082",
oauth_nonce="161822064",
oauth_callback="http%3A%2F%2Fexample.fitbit.com%2Fapp%2FcompleteAuthorization",
oauth_signature="Omf%2Bls2gn%2BDlghq245LRIyfMdd8%3D"
oauth_version="1.0"
A simple example would be helpful. Thank you.
I suggest using an OAuth library to handle the OAuth signature generation. It can be a pain in the ass to wrangle the Authorization header. I've used oauthconsumer with success.
Code sample:
OAConsumer *consumer = [[OAConsumer alloc] initWithKey:oauthConsumerKey secret:oauthConsumerSecret];
OAToken *token = [[OAToken alloc] initWithKey:oauthAccessToken secret:oauthAccessTokenSecret];
OAHMAC_SHA1SignatureProvider *provider = [[OAHMAC_SHA1SignatureProvider alloc] init];
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString] consumer:consumer token:token realm:nil signatureProvider:provider];
[request prepare];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
In this example, the 5 strings you will provide are:
oauthConsumerKey
oauthConsumerSecret
oauthAccessToken
oauthAccessTokenSecret
urlString
I am trying to do the same thing and oauthconsumer looks quite nice.
Is it because I am not getting the oauthAccessTokenSecret?
[edit] Yes, it was.
I keep getting:
"This page is no longer valid. It looks like you provided an invalid token or someone already used the token you provided. Please return to the site or application which sent you to this page and try again."
[edit] This is because it didn't have the correct token on the url string.
Hi you can get the working FitBit Oauth1.0 Authentication sample code from below link
https://github.com/KaranRajpoot/FitBit
Use OAuth.io, and the OAuth.io iOS SDK, to connect to FitBit.