如何转换NSUrl到NSString? [英] How to convert NSUrl to NSString?

查看:107
本文介绍了如何转换NSUrl到NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之后AVAssetExportSession 已完成导出视频。
我计划加载视频路径通过Youtube上传。
[GDataUtilities MIMETypeForFileAtPath:path defaultMIMEType:@video / mp4];
它只接受 NSString
可以将NSUrl转换为NSString以获取视频文件路径。



我已经尝试使用 NSString * path = [ExportoutputURL



这是代码

   - (void)exportDidFinish:(AVAssetExportSession *)session {
ExportoutputURL = session.outputURL;

_exporting = NO;
NSIndexPath * exportCellIndexPath = [NSIndexPath indexPathForRow:2 inSection:kProjectSection];
ExportCell * cell =(ExportCell *)[self.tableView cellForRowAtIndexPath:exportCellIndexPath];
cell.progressView.progress = 1.0;
[cell setProgressViewHidden:YES animated:YES];
[self updateCell:cell forRowAtIndexPath:exportCellIndexPath];

ALAssetsLibrary * library = [[ALAssetsLibrary alloc] init];
if([library videoAtPathIsCompatibleWithSavedPhotosAlbum:ExportoutputURL]){
[library writeVideoAtPathToSavedPhotosAlbum:ExportoutputURL
completionBlock:^(NSURL * assetURL,NSError * error){
dispatch_async(dispatch_get_main_queue ^ {
if(error){
NSLog(@writeVideoToAssestsLibrary failed:%@,error);
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:[error localizedDescription]
message:[error localizedRecoverySuggestion]
delegate:nil
cancelButtonTitle:@OK
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else {
_showSavedVideoToAssestsLibrary = YES;
ExportCell * cell =(ExportCell *)[self.tableView cellForRowAtIndexPath:exportCellIndexPath];
[cell setDetailTextLabelHidden:NO animated:YES];
[self updateCell:cell forRowAtIndexPath:exportCellIndexPath];
NSArray * modes = [[[NSArray alloc] initWithObjects:NSDefaultRunLoopMode,UITrackingRunLoopMode,nil] autorelease];
[self performSelector:@selector(hideCameraRollText)withObject:nil afterDelay:5.0 inModes:modes];
}
});

}];
}
[library release];
}

- (void)uploadVideoFile {

NSString * devKey = DEVELOPER_KEY;

GDataServiceGoogleYouTube * service = [self youTubeService];
[service setYouTubeDeveloperKey:devKey];

NSURL * url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:kGDataServiceDefaultUser];

//加载文件数据
NSString * path = [ExportoutputURL absoluteString]; // [[NSBundle mainBundle] pathForResource:@video_2451ofType:@mp4]; [mFilePathField stringValue];
NSFileHandle * fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
NSString * filename = [path lastPathComponent];

//收集mediaGroup所需的所有元数据
NSString * titleStr = @上传测试; // [mTitleField stringValue];
GDataMediaTitle * title = [GDataMediaTitle textConstructWithString:titleStr];

NSString * categoryStr = @Entertainment; // [[mCategoryPopup selectedItem ]resentObject];
GDataMediaCategory * category = [GDataMediaCategory mediaCategoryWithString:categoryStr];
[category setScheme:kGDataSchemeYouTubeCategory];

NSString * descStr = @GData Description; // [mDescriptionField stringValue];
GDataMediaDescription * desc = [GDataMediaDescription textConstructWithString:descStr];

NSString * keywordsStr = @RAGOpoR Demo; // [mKeywordsField stringValue];
GDataMediaKeywords * keywords = [GDataMediaKeywords keywordsWithString:keywordsStr];

BOOL isPrivate = NO; //([mPrivateCheckbox state] == NSOnState);

GDataYouTubeMediaGroup * mediaGroup = [GDataYouTubeMediaGroup mediaGroup];
[mediaGroup setMediaTitle:title];
[mediaGroup setMediaDescription:desc];
[mediaGroup addMediaCategory:category];
[mediaGroup setMediaKeywords:keywords];
[mediaGroup setIsPrivate:isPrivate];

NSString * mimeType = [GDataUtilities MIMETypeForFileAtPath:path
defaultMIMEType:@video / mp4];

//使用mediaGroup和文件
创建上传条目GDataEntryYouTubeUpload *条目;
entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup
fileHandle:fileHandle
MIMEType:mimeType
slug:filename];

SEL progressSel = @selector(ticket:hasDeliveredByteCount:ofTotalByteCount :);
[service setServiceUploadProgressSelector:progressSel];

GDataServiceTicket * ticket;
ticket = [service fetchEntryByInsertingEntry:entry
forFeedURL:url
delegate:self
didFinishSelector:@selector(uploadTicket:finishedWithEntry:error :)];
[self setUploadTicket:ticket];
GTMHTTPUploadFetcher * uploadFetcher =(GTMHTTPUploadFetcher *)[ticket objectFetch];

}

错误EXC_BAD_ACCESS在

  NSString * path = [ExportoutputURL absoluteString]; 


解决方案


将NSUrl转换为NSString以获取视频文件路径。


是的。发送一个 absoluteString 消息。


我试图使用NSString * path = [ExportoutputURL absoluteString];但它崩溃。


如果你想要一个路径,发送一个路径消息。表示URL的字符串通常不是有效路径;如果你想要一个路径,请问一个。



对于崩溃,它不意味着 absoluteString 错误。向NSURL对象发送 absoluteString 是获取表示URL的NSString对象的正确方法。

 

错误EXC_BAD_ACCESS

code> NSString * path = [ExportoutputURL absoluteString];


这可能意味着 ExportoutputURL 指向不是 nil 的东西,但也不是有效的对象。它可能在某个时候指向一个NSURL对象,但它现在不是。



我的猜测是问题是这样:


  ExportoutputURL = session.outputURL; 


您将URL分配给 ExportoutputURL 实例变量,但不保留对象或创建自己的副本。因此,你不拥有这个对象,这意味着你不保持它活着。它可能在任何时候死,很可能是在这个方法( exportDidFinish:)返回后。



崩溃是因为您稍后在URL对象已经死亡后调用 uploadVideoFile 。您仍然有一个指向它的指针,但该对象已不存在,因此向其发送消息 - 任何消息会导致崩溃。



有三种简单的解决方案:


  1. 在将URL分配给实例变量时保留URL对象。

  2. 创建自己的URL对象副本并将其分配给实例变量。

  3. 声明 ExportoutputURL 关键字 strong copy ,并将对象分配给属性,不是实例变量。这将调用属性的setter,如果你合成它或正确实现它,将保留或复制你的URL。

无论哪种方式,你将拥有该对象,并将保持它活着,直到你释放它。因此,你需要在完成它后释放它(在 dealloc ,如果不是更早),这样你就不会泄漏它。



这一切假设你不使用ARC。如果您使用Xcode 4.2或更高版本,并且可以要求iOS 4或更高版本,您应该将您的项目迁移到ARC,因为它使得这么多的事情更简单。如果您使用ARC,则不需要保留或复制此对象,这意味着现在迁移到ARC是第四个解决方案(但当然是更大规模的解决方案)。


After AVAssetExportSession has complete export video. I have plan to garb Video Path to upload via Youtube. but [GDataUtilities MIMETypeForFileAtPath:path defaultMIMEType:@"video/mp4"]; it only accept NSString. Is it possible to convert NSUrl in to NSString for video file path.

i have try to use NSString *path = [ExportoutputURL absoluteString]; but it crash.

Here is the Code

- (void)exportDidFinish:(AVAssetExportSession*)session {
    ExportoutputURL = session.outputURL;

    _exporting = NO;
    NSIndexPath *exportCellIndexPath = [NSIndexPath indexPathForRow:2 inSection:kProjectSection];
    ExportCell *cell = (ExportCell*)[self.tableView cellForRowAtIndexPath:exportCellIndexPath];
    cell.progressView.progress = 1.0;
    [cell setProgressViewHidden:YES animated:YES];
    [self updateCell:cell forRowAtIndexPath:exportCellIndexPath];

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:ExportoutputURL]) {
        [library writeVideoAtPathToSavedPhotosAlbum:ExportoutputURL
                                    completionBlock:^(NSURL *assetURL, NSError *error){
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            if (error) {
                                                NSLog(@"writeVideoToAssestsLibrary failed: %@", error);
                                                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[error localizedDescription]
                                                                                                    message:[error localizedRecoverySuggestion]
                                                                                                   delegate:nil
                                                                                          cancelButtonTitle:@"OK"
                                                                                          otherButtonTitles:nil];
                                                [alertView show];
                                                [alertView release];
                                            }
                                            else {
                                                _showSavedVideoToAssestsLibrary = YES;
                                                ExportCell *cell = (ExportCell*)[self.tableView cellForRowAtIndexPath:exportCellIndexPath];
                                                [cell setDetailTextLabelHidden:NO animated:YES];
                                                [self updateCell:cell forRowAtIndexPath:exportCellIndexPath];
                                                NSArray *modes = [[[NSArray alloc] initWithObjects:NSDefaultRunLoopMode, UITrackingRunLoopMode, nil] autorelease];
                                                [self performSelector:@selector(hideCameraRollText) withObject:nil afterDelay:5.0 inModes:modes];
                                            }
                                        });

                                    }];
    }
    [library release];
}

- (void)uploadVideoFile {

    NSString *devKey = DEVELOPER_KEY;

    GDataServiceGoogleYouTube *service = [self youTubeService];
    [service setYouTubeDeveloperKey:devKey];

    NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:kGDataServiceDefaultUser];

    // load the file data
    NSString *path = [ExportoutputURL absoluteString];//[[NSBundle mainBundle] pathForResource:@"video_2451" ofType:@"mp4"];//[mFilePathField stringValue];
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    NSString *filename = [path lastPathComponent];

    // gather all the metadata needed for the mediaGroup
    NSString *titleStr = @"Upload Test";//[mTitleField stringValue];
    GDataMediaTitle *title = [GDataMediaTitle textConstructWithString:titleStr];

    NSString *categoryStr = @"Entertainment";//[[mCategoryPopup selectedItem] representedObject];
    GDataMediaCategory *category = [GDataMediaCategory mediaCategoryWithString:categoryStr];
    [category setScheme:kGDataSchemeYouTubeCategory];

    NSString *descStr = @"GData Description";//[mDescriptionField stringValue];
    GDataMediaDescription *desc = [GDataMediaDescription textConstructWithString:descStr];

    NSString *keywordsStr = @"RAGOpoR Demo";//[mKeywordsField stringValue];
    GDataMediaKeywords *keywords = [GDataMediaKeywords keywordsWithString:keywordsStr];

    BOOL isPrivate = NO;//([mPrivateCheckbox state] == NSOnState);

    GDataYouTubeMediaGroup *mediaGroup = [GDataYouTubeMediaGroup mediaGroup];
    [mediaGroup setMediaTitle:title];
    [mediaGroup setMediaDescription:desc];
    [mediaGroup addMediaCategory:category];
    [mediaGroup setMediaKeywords:keywords];
    [mediaGroup setIsPrivate:isPrivate];

    NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:path
                                               defaultMIMEType:@"video/mp4"];

    // create the upload entry with the mediaGroup and the file
    GDataEntryYouTubeUpload *entry;
    entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup
                                                    fileHandle:fileHandle
                                                      MIMEType:mimeType
                                                          slug:filename];

    SEL progressSel = @selector(ticket:hasDeliveredByteCount:ofTotalByteCount:);
    [service setServiceUploadProgressSelector:progressSel];

    GDataServiceTicket *ticket;
    ticket = [service fetchEntryByInsertingEntry:entry
                                      forFeedURL:url
                                        delegate:self
                               didFinishSelector:@selector(uploadTicket:finishedWithEntry:error:)];
    [self setUploadTicket:ticket];
    GTMHTTPUploadFetcher *uploadFetcher = (GTMHTTPUploadFetcher *)[ticket objectFetcher];

}

Error EXC_BAD_ACCESS at

NSString *path = [ExportoutputURL absoluteString];

解决方案

Is it possible to convert NSUrl in to NSString for video file path.

Yes. Send it an absoluteString message.

i have try to use NSString *path = [ExportoutputURL absoluteString]; but it crash.

If you want a path, send the URL a path message. A string representing a URL is generally not a valid path; if you want a path, ask it for one.

As for the crash, it does not mean absoluteString is wrong. Sending absoluteString to an NSURL object is the correct way to get an NSString object that represents the URL. The problem is somewhere else.

Error EXC_BAD_ACCESS at

NSString *path = [ExportoutputURL absoluteString];

This probably means that ExportoutputURL points to something that is not nil but is also not a valid object. It might have pointed to an NSURL object at some point, but it doesn't now.

My guess would be that the problem is this:

ExportoutputURL = session.outputURL;

You assign the URL to the ExportoutputURL instance variable, but you don't retain the object or make your own copy. Therefore, you don't own this object, which means you are not keeping it alive. It may die at any time, most probably after this method (exportDidFinish:) returns.

The crash is because you call uploadVideoFile later, after the URL object has already died. You still have a pointer to it, but that object no longer exists, so sending a message to it—any message—causes a crash.

There are three simple solutions:

  1. Retain the URL object when you assign it to your instance variable.
  2. Make your own copy of the URL object and assign that to the instance variable.
  3. Declare ExportoutputURL as a property, with either the strong keyword or the copy keyword, and assign the object to the property, not the instance variable. That will call the property's setter, which, if you synthesize it or implement it correctly, will retain or copy the URL for you.

Either way, you will own the object, and that will keep it alive until you release it. Accordingly, you will need to release it when you are done with it (in dealloc, if not earlier), so that you don't leak it.

This all assumes that you are not using ARC. If you are using Xcode 4.2 or later, and can require iOS 4 or later, you should migrate your project to ARC, as it makes so many things much simpler. You would not need to retain or copy this object if you were using ARC, which means that migrating to ARC now is a fourth solution (but certainly a larger-scale one).

这篇关于如何转换NSUrl到NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆